package com.carkeeper.order.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//@Configuration
public class RabbitMQConfig {
    /*
        订单状态
     */
    //定义队列
    public static final String ORDER_QUEUE = "order_queue";
    //声明队列
    @Bean
    public Queue orderQueue() {
        //true:开启持久化
        return new Queue(ORDER_QUEUE,true);
    }

    /*
        超时订单
     */
    //定义
    //队列
    public static final String OVERTIME_ORDER_QUEUE = "overtime_order_queue";
    //死信队列
    public static final String XDL_OVERTIME_ORDER_QUEUE = "xdl_overtime_order_queue";
    //死信交换机
    public static final String XDL_OVERTIME_ORDER_EXCHANGE = "xdl_overtime_order_exchange";
    //路由key
    public static final String DEAD_LETTER_REDIRECT_ROUTING_KEY = "TKEY_R";

    //声明
    //队列
    @Bean(OVERTIME_ORDER_QUEUE)
    public Queue overtimeOrderQueue() {
        //true:开启持久化
        return new Queue(OVERTIME_ORDER_QUEUE,true);
    }
    //死信交换机
    @Bean(XDL_OVERTIME_ORDER_EXCHANGE)
    public Exchange xdlOvertimeOrderExchange() {
        return ExchangeBuilder.directExchange(XDL_OVERTIME_ORDER_EXCHANGE).durable(true).build();
    }

    //死信队列
    @Bean(XDL_OVERTIME_ORDER_QUEUE)
    public Queue xdlOvertimeOrderQueue() {
        Map<String, Object> args = new HashMap<>();
        //死信交换机
        args.put("x-dead-letter-exchange", XDL_OVERTIME_ORDER_EXCHANGE);
        //路由key
        args.put("x-dead-letter-routing-key", DEAD_LETTER_REDIRECT_ROUTING_KEY);
        //存活时间24小时
        args.put("x-message-ttl", 1000*60*60*24);
        return QueueBuilder.durable(XDL_OVERTIME_ORDER_QUEUE).withArguments(args).build();
    }

    //死信队列绑定死信交换机
    @Bean
    public Binding xdlQueueBindXdlExchange(@Qualifier(XDL_OVERTIME_ORDER_QUEUE) Queue queue, @Qualifier(XDL_OVERTIME_ORDER_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("").noargs();
    }
    //队列绑定死信交换机
    @Bean
    public Binding queueBindXdlExchange(@Qualifier(OVERTIME_ORDER_QUEUE) Queue queue, @Qualifier(XDL_OVERTIME_ORDER_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_REDIRECT_ROUTING_KEY).noargs();
    }

}
